<?php
/**
 * Created by PhpStorm.
 * User: fengzi
 * Date: 2019/5/31
 * Time: 14:36
 */

namespace app\vehicle\logic;
use app\common\model\Admin;
use app\common\model\Site;
use app\common\model\Street;
use app\common\model\Config;
use app\common\model\SiteTeam;
use app\common\model\Organization;
use app\vehicle\model\ServiceType;
use app\vehicle\model\User;
use app\vehicle\model\UserTpl;
use app\vehicle\model\UserIntegral;
use app\vehicle\model\UserIntegralLog;
use app\vehicle\model\Message;
use app\vehicle\model\Volunteer;
use app\vehicle\model\Practice;
use app\common\model\Passbook;
use app\vehicle\model\SmsLog;
use app\vehicle\model\Feedback;
use app\vehicle\model\CouponUser;
use app\vehicle\logic\TplLogic;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class userLogic
{
    public function setPassbookVolunteer($data,$uid){
        $site_id = Site::where('find_in_set('.$uid.',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id');
        if(!$site_id && !$oid){
            return '暂无权限';
        }
        $user_id = User::insertGetId([
            'nick_name'=>$data['realname'],
            'mobile'=>$data['mobile'],
            'create_time'=>time()
        ]);
        $data['nums'] = str_pad(db('volunteer_num')->order('id desc')->value('id')+1,6,'0',STR_PAD_LEFT);
        $data['user_id'] = $user_id;
        $data['is_after'] = 1;
        $data['update_time'] = time();
        $res = Volunteer::where('id','=',$data['id'])->update($data);
        return 1;
    }
    public function checkRole($data,$uid){
        $site_id = Site::where('find_in_set('.$uid.',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id');
        if(!$site_id && !$oid){
            return '暂无权限';
        }
        $info = Volunteer::where('id','=',$data['vid'])->find();
        if(!$info['id']){
          // return '该存折不存在';
        }
        return 1;
    }
    public function addPassbook($data,$uid){
        $site_id = Site::where('find_in_set('.$uid.',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id');
        if(!$site_id && !$oid){
            return '暂无权限';
        }
        $data['uid'] = Volunteer::where('id','=',$data['vid'])->value('user_id');
        if(!$data['uid']){
            return '该存折不存在';
        }
        $data['sign_time'] = strtotime($data['sign_time']);
        $data['retreat_time'] = strtotime($data['retreat_time']);
        $v['s_time'] = $data['sign_time'];
        $v['e_time'] = $data['retreat_time'];
        $times = 0;
        $info = Practice::where('id','eq',$v['aid'])->find();
        if($v['e_time']>0 && $v['e_time']>$v['s_time']){
            $e_time = $v['e_time'];
            if($v['e_time']>$info['activity_end_time']){
                $e_time = $info['activity_end_time'];
            }
            $s_time = $v['s_time'];
            if($v['s_time']<$info['activity_use_time']){
                $s_time = $info['activity_use_time'];
            }
            $times = round(($e_time-$s_time)/3600);
        }
        $data['time'] = $times>0?$times:0;
        if ($data['type'] == 1) {
            $duration = Config::where('key', 'eq', 'duration1')->value('value') ?? 1;
        } else {
            $duration = Config::where('key', 'eq', 'duration2')->value('value') ?? 1;
        }
        if($times>0) {
            $data['integral'] = $times * $duration;
        }

        $data['create_time'] = time();
        $data['site_id'] = $site_id?$site_id:$oid;
        Passbook::insert($data);
        return 1;
    }
    public function getSitePractice($uid,$data){
        $site_id = Site::where('find_in_set('.$uid.',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id');
        if($site_id){
            $where[] = ['site_id','=',$site_id];
        }else if($oid){
            $where[] = ['oid','=',$oid];
        }
        $data['keyword'] && $where[] = ['title','like','%'.$data['keyword'].'%'];
        $list = Practice::where($where)->order('id desc')->select();
        return $list;
    }
    public function getSiteVolunteer($uid){
        $site_id = Site::where('find_in_set('.$uid.',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id');
        if($site_id){
            $list = Volunteer::where('site_id','=',$site_id)->where('is_after','=',1)->order('id desc')->select();
        }else if($oid){
            $list = Volunteer::where('oid','=',$oid)->where('is_after','=',1)->order('id desc')->select();
        }
        foreach($list as $k=>$v){
            $integral = User::where('id','=',$v['user_id'])->value('integral');
            $list[$k]['passbook'] = $v['realname'].'(积分:'.$integral.')';
        }
        return $list;
    }
    public function addVolunteer($data,$uid){
        $check = Volunteer::where('mobile','=',$data['mobile'])->count();
        if($check){
            return '该手机号已存在';
        }

        $id = User::insertGetId([
            'nick_name'=>$data['realname'],
            'mobile'=>$data['mobile'],
            'create_time'=>time()
        ]);
        $data['nums'] = str_pad(db('volunteer_num')->order('id desc')->value('id')+1,6,'0',STR_PAD_LEFT);
        $data['site_id'] = Site::where('find_in_set('.$uid.',pass_id)')->value('id')??0;
        $data['oid'] = SiteTeam::where('find_in_set('.$uid.',pass_id)')->value('id')??0;
        $data['user_id'] = $id;
        $data['is_after'] = 1;
        $data['create_time'] = time();
        $res = Volunteer::insert($data);
        return 1;
    }
    public function setTpl($data,$user_id){
//        $insert['user_id'] = $user_id;
//        $insert['form_id'] = $data['form_id'];
//        $insert['create_time'] = time();
//        $insert['status'] = 0;
//        $data['form_id'] && UserTpl::insert($insert);
//        $info = db('practice')->where('id',1)->find();
//        TplLogic::applySuccess('oE4HI5YIX1qSfK2N4z_d8OCgTy5w',$data['form_id'],$info);

        //return 1;
    }
    public function feedback($data,$user_id){
        $data['user_id'] = $user_id;
        $data['create_time'] = time();
        return Feedback::insert($data);
    }
    public function getSite($name){
        $where[] = ['status','eq',1];
        $name && $where[] = ['name','like','%'.$name.'%'];
        return Site::where($where)->select();
    }
    public function getStreet(){
        $street = Street::where('status','eq',1)->order('id asc')->select();
        $s[] = ['id'=>0,'name'=>'全部'];
        foreach($street as $k=>$v){
            $s[] = $v;
        }
        return $s;
    }
    public function getOrganization($name){
        $where[] = ['status','eq',1];
        $name && $where[] = ['name','like','%'.$name.'%'];
        return SiteTeam::where($where)->select();
    }
    public function getService(){
        return ServiceType::select();
    }
    public function setVolunteer($data,$user_id){
        $id = Volunteer::where('user_id','eq',$user_id)->value('id');
        $data['user_id'] = $user_id;
        $data['o_status'] = 0;
        $data['new_oid'] = $data['oid'];
        $data['new_site_id'] = $data['site_id'];
        $data['oid'] = 0;
        $data['site_id'] = 0;
        if($id){
            $data['update_time'] = time();
            $data['status'] = 0;
            Volunteer::where('id','eq',$id)->update($data);
        }else{
            $data['create_time'] = time();
            Volunteer::insert($data);
        }
        return 1;
    }
    public function bingVolunteer($data,$user_id){
        $id = Volunteer::where('user_id','eq',$user_id)->value('id');
        $data['update_time'] = time();
        $data['new_oid'] = $data['oid'];
        $data['new_site_id'] = $data['site_id'];
        $data['oid'] = 0;
        $data['is_party'] = $data['is_party'];
        $data['site_id'] = 0;
        $data['o_status'] = 0;
        Volunteer::where('id','eq',$id)->update($data);
        return 1;
    }
    public function setVolunteerTeam($data,$user_id){
        $id = Volunteer::where('user_id','eq',$user_id)->value('id');
        if(!$id){
            return '请先申请志愿者';
        }
        $data['site_id'] = $data['site_id'];
        $data['status'] = 0;
        Volunteer::where('id','eq',$id)->update($data);
        return 1;
    }
    public function login($data){
        $info = Volunteer::field('*,status as sid')->where('username','eq',$data['username'])->find();
        if(!$info['id']){
            return '用户名不存在';
        }else if(md5($data['password'])!=$info['password']){
            return '密码错误';
        }else if($info['sid']<1){
            return '你的账号还在审核中';
        }else if($info['sid']==2){
            return '你的账号还在审核不通过';
        }
        $info['token'] = md5($info['id']);
        Volunteer::where('id','eq',$info['id'])->update(['token'=>md5($info['id'])]);
        return $info;
    }
    
    public function setCoupon($user_id){
        $list = Coupon::where('status','eq',1)->select();
        foreach($list as $k=>$v){
            $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";//qwertyuiopasdfghjklzxcvbnm
            $resume = substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),10);
            $insert['resume'] = $resume;
            $insert['user_id'] = $user_id;
            $insert['title'] = $v['title'];
            $insert['coupon_id'] = $v['id'];
            $insert['coupon_price'] = $v['coupon_price'];
            $insert['use_min_price'] = $v['use_min_price'];
            $insert['start_time'] = time();
            $insert['end_time'] = $insert['start_time']+$v['coupon_time']*86400;
            $insert['create_time'] = $insert['start_time'];
            CouponUser::insert($insert);
        }
    }
    //获取个人信息
    public function getUserInfo($user_id){
        $user = User::get($user_id);
        $user['info'] = Volunteer::where('user_id','eq',$user_id)->find();

        $t = strtotime(date('Y-m-d'));
        $user['is_sign'] = UserIntegralLog::where('user_id','eq',$user_id)->where('type_id','eq',0)->where('create_time','>',$t)->count();
        $site_status = 0;
        $user['volunteer'] = Volunteer::where('user_id','eq',$user_id)->field('status,status as sid,is_add,oid,o_status,new_oid,new_site_id,realname,mobile,id_card,skill')->find();

        if($user['site_id'] && $user['site_status']==1){
            $site_status = 1;
        }else if($user['site_id'] && $user['site_status']==2){
            $site_status = 2;
        }else if($user['site_id'] && $user['site_status']==0){
            $site_status = 3;
        }

        if($user['volunteer']){
            if($user['volunteer']['sid']){
                $site_status = 1;
            }
            $user['volunteer']['status'] = $user['volunteer']['sid'];
            if($user['volunteer']['is_add']==1 && $user['volunteer']['sid']==1 && $user['volunteer']['oid']){
                //$user['team_admin'] = $user['volunteer']['oid'];
            }
            $user['volunteer']['new_oid'] && $user['team_name'] = SiteTeam::where('id','eq',$user['volunteer']['new_oid'])->value('name');
            $user['volunteer']['new_site_id'] && $user['team_name'] = Site::where('id','eq',$user['volunteer']['new_site_id'])->value('name');
        }
        $user['ss'] = $site_status;
        //$user['volunteer'] = 0;
        if($user['team_admin']){
            $count1= Volunteer::where('oid','eq',$user['team_admin'])->where('user_id','neq',$user_id)->count();
            $count2= User::where('team_admin','eq',$user['team_admin'])->count();
            $user['team_num'] = $count1;
            $user['team_activity'] = SiteTeam::where('id','eq',$user['team_admin'])->value('number')??0;
            $all_id = Volunteer::where('site_id','eq',$user['team_admin'])->column('user_id');
            $user['duration'] = $user['duration']+User::where('id','in',implode(',',$all_id))->sum('duration');
            $user['integral'] = $user['integral']+User::where('id','in',implode(',',$all_id))->sum('integral');
            $user['team_name'] = SiteTeam::where('id','eq',$user['team_admin'])->value('name');
            $user['team_status'] = SiteTeam::where('id','eq',$user['team_admin'])->value('status');
        }else{
            $user['team_status'] = 0;
            $user['team_num'] = 0;
        }
        $user['is_scan'] = Site::where('find_in_set('.$user['id'].',role_id)')->value('id');
        $site_id = Site::where('find_in_set('.$user['id'].',pass_id)')->value('id');
        $oid = SiteTeam::where('find_in_set('.$user['id'].',pass_id)')->value('id');
        if($site_id){
            $user['is_pass'] = $site_id;
        }else if($oid){
            $user['is_pass'] = $oid;
        }else{
            $user['is_pass'] = 0;
        }
        return $user;
    }
    public function getTeamInfo($user){
        return SiteTeam::where('id','eq',$user['team_admin'])->find();
    }
    public function getShopInfo($data){
        $user = Admin::where('id','eq',$data['shop_id'])->find();
        $user['logo'] = config('database.img_url').$user['logo'];
        $user['realname'] = $user['nick_name'];

        $time = strtotime(date('Y-m-d'));
        $user['sign_in'] = UserIntegral::where('create_time','gt',$time)->where('shop_id','eq',$data['shop_id'])->where('type_id','eq',2)->count();

        return $user;
    }
    public function signIn($data){
        $integral = db('config')->where('id','eq',14)->value('value');
        $time = strtotime(date('Y-m-d'));
        $check = UserIntegral::where('create_time','gt',$time)->where('shop_id','eq',$data['shop_id'])->where('type_id','eq',2)->count();
        if($check){
            return '已簽到';
        }
        if($integral) {
            $insert['shop_id'] = $data['shop_id'];
            $insert['order_id'] = 0;
            $insert['type_id'] = 2;
            $insert['create_time'] = time();
            $insert['integral'] = $integral;
            UserIntegral::insert($insert);
            Admin::where('id', 'eq', $data['shop_id'])->setInc('integral', intval($integral));
        }
        return 1;
    }
    public function setInfo($data,$user_id){
        $up['sex'] = $data['sex'];
        $up['birthday'] = strtotime($data['birthday']);
        $up['grade'] = $data['grade'];
        $up['area'] = $data['area'];
        $up['is_party'] = $data['is_party'];
        $up['school'] = $data['school'];
        User::where('id','eq',$user_id)->update($up);
        return 1;
    }
    public function setForm($data,$user_id){
        $up['form_id'] = $data['form_id'];
        return User::where('id','eq',$user_id)->update($up);
    }
    //获取用户是否审核通过
    public function getUserAgent($business_id){
        $result = UserInfo::where('id','eq',$business_id)->value('status');
        return $result;
    }

    public function setMobile($mobile,$user_id){
        return User::where('id','eq',$user_id)->update(['mobile'=>$mobile]);
    }

    public function getMessageList($page,$user_id){
        return Message::where('user_id','eq',$user_id)->where('type_id','eq',1)->order('id desc')->page($page,10)->select();
    }
    //获取验证码
    public function sendAliDaYuAuthCode($mobile,$user_id){
        $time = time()-300;
        $check = SmsLog::where([['user_id','eq',$user_id],['create_time','gt',$time]])->count();
        if($check){
            return '重复获取，请稍后再试';
        }
        $accessKeyId = 'LTAI7EjDYEEljbu7';
        $accessSecret = 'iaHezldXthyqgygK85tZ0ls9xxwD7Z';
        $signName = '信禾';
        $templateCode = 'SMS_109570056';
        $authCodeMT = mt_rand(100000,999999);
        $jsonTemplateParam = json_encode(['code'=>$authCodeMT]);
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->regionId('cn-hangzhou')
            ->asGlobalClient();
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'RegionId' => 'cn-hangzhou',
                        'PhoneNumbers' => $mobile,
                        'SignName' => $signName,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => $jsonTemplateParam
                    ],
                ])
                ->request();
            $opRes = $result->toArray();
            if ($opRes && $opRes['Code'] == "OK"){
                $insert['code'] = $authCodeMT;
                $insert['user_id'] = $user_id;
                $insert['create_time'] = time();
                SmsLog::insert($insert);
            }
            return 'success';
        } catch (ClientException $e) {
            return $e->getErrorMessage();
        } catch (ServerException $e) {
            return $e->getErrorMessage();
        }
    }
    public function judgeCode($code,$user_id){
        $result = SmsLog::where('user_id','eq',$user_id)->order('id desc')->find();
        if($result['code']==$code){
            $time = time();
            if($result['create_time']<$time-3600){
                return '验证码已过期';
            }else{
                return 'success';
            }
        }else{
            return '验证码错误';
        }
    }

    public function setTeam($data,$user_id){
        $data['user_id'] = $user_id;
        $data['create_time'] = time();
        $check = SiteTeam::where('user_id','eq',$user_id)->find();
        if($check['status']==2){
            return '您的申请被拒绝，请联系管理员。';
        }else if($check['id']){
            return '您已申请了团队';
        }
        $check = SiteTeam::where('name','eq',$data['name'])->count();
        if($check){
            return '该团队已存在';
        }
        if($data['s_type']==1){
            $data['oid'] = $data['sid'];
            unset($data['sid']);
        }
        $site = new SiteTeam();
        $site->allowField(true)->save($data);
        return 1;
    }
}